package com.jzo2o.trade.controller;

import com.jzo2o.trade.service.IPaySuccessService;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * \* User: chy
 * \* Date: 2025/10/8  17:40
 * \* Description: 微信支付成功后的回调通知
 * \
 */
@RestController
@RequestMapping("/wxpay/notify")
@Slf4j
public class WechatNotifyController {

    @Resource
    private NotificationConfig notificationConfig;
    @Resource
    private IPaySuccessService paySuccessService;
    @PostMapping()
    public String payNotify(@RequestBody String body, HttpServletRequest request) throws Exception {
        log.info("收到微信回调消息");

        // 从HTTP头部获取微信支付签名相关信息
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");

        // 构造请求参数对象，用于后续验签和解密
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)          // 微信平台证书序列号
                .nonce(wechatpayNonce)                  // 随机字符串
                .signature(wechatSignature)             // 签名信息
                .timestamp(wechatTimestamp)             // 时间戳
                .body(body)                             // 请求体内容
                .build();

        // 初始化通知解析器
        NotificationParser parser = new NotificationParser(notificationConfig);
        try {
            // 验签、解密并将结果转换为Transaction对象
            Transaction transaction = parser.parse(requestParam, Transaction.class);

            // 获取支付服务订单号
            String outTradeNo = transaction.getOutTradeNo();
            // 获取微信支付订单号
//            String transactionId = transaction.getTransactionId();
            log.info("开始处理订单后续逻辑：{}", outTradeNo);

            // TODO: 在此处添加订单处理逻辑，如更新数据库订单状态等
            // 修改trading 表状态 和 填充transactionId
            paySuccessService.updateTradingState(outTradeNo);

        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            log.error("微信支付通知验签失败", e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).toString();
        }

        // 处理成功，返回 200 OK 状态码告知微信服务器已成功接收通知
        return ResponseEntity.status(HttpStatus.OK).toString();
    }
}
